<?php

namespace App\Library\Message\Channels;

use App\Components\System\Models\WeChatMessageSendResult;
use EasyWeChat\Kernel\Support\Collection;
use Illuminate\Notifications\Notification;

class WeChatChannel
{
    /**
     * @var \EasyWeChat\OfficialAccount\CustomerService\Client
     */
    private $customerService;

    public function __construct()
    {
        $this->customerService = app(\EasyWeChat\OfficialAccount\Application::class)->customer_service;
    }

    public function send($notifiable, Notification $notification)
    {
        if (! $to = $notifiable->routeNotificationFor('we_chat', $notification)) {
            return;
        }

        /** @var \EasyWeChat\Kernel\Messages\Message|string $message */
        $message = $notification->toWeChat($notifiable);

        if (is_null($message) || empty($message)) {
            return;
        }

        if (is_array($message)) {
            $result = [];
            foreach ($message as $row) {
                $result[] = $this->customerService->message($row)->to($to)->send();
            }
        } else {
            $result = $this->customerService->message($message)->to($to)->send();
        }

        if ($result instanceof Collection) {
            WeChatMessageSendResult::create([
                'open_id' => $to,
                'message' => get_class($notification),
                'err_code' => $result->errcode,
                'err_msg' => $result->errmsg,
            ]);
        }

        if (method_exists($notification, 'onSendFinished')) {
            $notification->onSendFinished('we_chat', $result);
        }
    }
}
